package com.example.fund;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.example.fund.amplitude.Amplitude;
import com.example.fund.amplitude.TimePeriod;
import com.example.fund.dialogFragment.DialogFragmentEx;
import com.example.fund.fundstocks.FundStocksUtil;
import com.example.fund.fundstocks.FundStocks;
import com.example.fund.fundtrade.FundTradeDialog;
import com.example.fund.fundtrade.FundTradeList;
import com.example.fund.info.FOFInfo;
import com.example.fund.info.FundInfo;
import com.example.fund.sqlquery.SqlQueryList;
import com.example.fund.updatestategy.FundNetValueUpdateStrategy;
import com.example.fund.updatestategy.FuturesIndexStrategy;
import com.example.fund.updatestategy.MixIndexStrategy;
import com.example.fund.updatestategy.UpdateStrategy;
import com.example.fund.util.DBManager;
import com.example.fund.util.FOFUtil;
import com.example.fund.util.FundUtil;
import com.example.fund.util.FundUtil1;
import com.example.fund.util.StringUtil;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import static com.example.fund.util.FOFUtil.getFOFInfoList;


public class MainActivity extends BaseActivity {
	
	private Map<String,Object> dataContext;
	
	private LinearLayout root;
	private LinearLayout layoutTime;
	private HorizontalScrollView scrolIndex;
	private LinearLayout layoutIndex;
	private LinearLayout layoutIndex1;
	
	//自定义弹出选择框
	private PopupWindow popupWindow;
	private ListView popupList;
	
	//基金列表弹出选择框
	private PopupWindow fundPopup;
	private ListView fundListView;
//	private CheckBox chxFund;
	private TextView fundSelect;
	private int selectIdx = -1;

	private int bg1 = Color.rgb(5, 167, 247);
	private int bg2 = Color.rgb(233,244,251);
	private String[] positiveArr = Constant.positiveArr;
	private String[] negativeArr = Constant.negativeArr;
	private String[] annualArr = Constant.annualArr;
	private TextView timePeriod;
	private TextView startDate;
	private TextView endDate;
	private TextView positiveRate;
	private TextView negativeRate;
	private TextView positiveRate1;
	private TextView negativeRate1;
	private TextView currDate;
	private TextView fresh;
	private TextView annualLine;
	
	private List<CheckBox> chxIndexList = new LinkedList<CheckBox>();
//	private String[][] indexNumbers = Constant.indexNumbers;
	private CheckBox chxDisplayDiffLine;
	private CheckBox chxChartsLine;
	private CheckBox chxSimpleLine;
	
	//数据
	private List<String> dateList;//全部的交易日期
	private List<String> timePeriodList;//预定义区间
	private Map<String,String> periodMap;//预定义区间
	private List<Map<String, Object>> fundList;//基金列表
	
	//主要指数
	private List<FundInfo> selectFundInfoList = new LinkedList<FundInfo>();
	private FundInfo fundInfo;
	private FundInfo annualFund;
	
	private TextView openFundIndex;//打开主页
	private EditText filterText;//过滤关键字
	private TextView orderFields;//排序
	private List<String> orderFieldList = new LinkedList<String>();
	
	private DrawView drawView;
	private MagnifierDrawView magnifierDrawView;
	
	//屏蔽
	private CheckBox chxZoomIn;
	//屏蔽
	private CheckBox chxCandle;
	//对数坐标
	private CheckBox chxLogY;
	//基金持仓按钮
	private TextView txtFundStocks;
	//SQL查询按钮
	private TextView txtSqlQuery;
	//打开交易记录列表
	private TextView txtFundTrade;
	
	private TextView txtIndexSet;
	
	//当前点击的TextViewY
	private TextView tv;
	
	//drawView的onTouch事件专用
	private float x = -1;
	private float y = -1;
	private int startIndex = 0;
	private int endIndex = 0;
	private long firClick = 0;  
	private long secClick = 0; 
	
   	private boolean[] orderCheckedItems;
   	private CharSequence[] orderItems;
   	
   	private String remindStartDate = "";
   	
//   	private TextView correlTextView;//指数之间的相关系数
   	//交易
	private String tradeNumber;
	private String tradeDate;
   	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        setContentView(R.layout.activity_main);
 //       FundUtil.clearRubbishData();
        dataContext = new HashMap<String,Object>();
 //       boolean flag = FundUtil.clearRubbishData();
        initDataAndView();
        initIndexView();
        initListener();
    }

    /**
     * 初始化界面控件及数据
     */
    private void initDataAndView()
    {
    	//view
    	root = (LinearLayout)findViewById(R.id.root);
    	root.setBackgroundColor(bg2);
    	layoutTime = (LinearLayout)findViewById(R.id.layoutTime);
 //   	layoutTime.setBackgroundColor(bg1);
    	scrolIndex = (HorizontalScrollView)findViewById(R.id.scrolIndex);
 //   	scrolIndex.setBackgroundColor(bg1);
    	layoutIndex1 = (LinearLayout)findViewById(R.id.layoutIndex1);
  //  	layoutIndex1.setBackgroundColor(bg2);
    	layoutIndex = (LinearLayout)findViewById(R.id.layoutIndex);
  //  	layoutIndex.setBackgroundColor(bg2);
    	drawView = (DrawView) findViewById(R.id.drawView);
    	magnifierDrawView = (MagnifierDrawView) findViewById(R.id.magnifierDrawView);
    	
    	//设置drawView的高度
/*        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) drawView.getLayoutParams();  
        layoutParams1.height = height/3;  
        drawView.setLayoutParams(layoutParams1); */
    	
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(30, 0, 0, 0);
    	
    	timePeriod = (TextView) findViewById(R.id.timePeriod);
    	startDate = (TextView) findViewById(R.id.startDate);
    	endDate = (TextView) findViewById(R.id.endDate);
    	positiveRate = (TextView) findViewById(R.id.positiveRate);
    	positiveRate.setLayoutParams(layoutParams);
    	negativeRate = (TextView) findViewById(R.id.negativeRate);
		positiveRate1 = (TextView) findViewById(R.id.positiveRate1);
		positiveRate1.setLayoutParams(layoutParams);
		negativeRate1 = (TextView) findViewById(R.id.negativeRate1);
    	currDate = (TextView) findViewById(R.id.currDate);
    	fresh = (TextView) findViewById(R.id.fresh);
		annualLine = (TextView) findViewById(R.id.annualLine);
//    	correlTextView = (TextView) findViewById(R.id.correlTextView);;
    	
    	//初始化自定义下拉框
        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.popupwindow, null);  
        contentView.setBackgroundColor(bg2);  
        popupWindow = new PopupWindow(root, 400, 900);  
        popupWindow.setContentView(contentView); 
        popupList = (ListView) contentView.findViewById(R.id.popupList);
        popupList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        popupWindow.setFocusable(true);  
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        
        //初始化基本列表选择框
 //       chxFund = (CheckBox)findViewById(R.id.chxFund);
        fundSelect = (TextView) findViewById(R.id.fundSelect);
        fundSelect.setTextColor(FundUtil1.getIndexColor("0000000"));
        View contentView1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.fundpopup, null);  
        contentView1.setBackgroundColor(bg2);  
        fundPopup = new PopupWindow(root, 400, 900);  
        fundPopup.setContentView(contentView1); 
        fundListView = (ListView) contentView1.findViewById(R.id.fundList);
        fundListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        fundPopup.setFocusable(true);  
        fundPopup.setOutsideTouchable(true);
        fundPopup.setBackgroundDrawable(new ColorDrawable(0));
    	
    	//数据
    	dateList = FundUtil.getSHIndexDateList();
 //   	timePeriodList = TimePeriodUtil.getTimePeriodList(dateList);
    	TimePeriod atimePeriod = new TimePeriod(new Amplitude());
    	timePeriodList = atimePeriod.getTimePeriodList(dateList);
    	periodMap = atimePeriod.getTimePeriodMap(dateList);
    	String timePeriodStr = periodMap.get("牛1>今");
		if(timePeriodStr!=null && timePeriodStr.indexOf(":")>0)
		{
			timePeriod.setText("牛1>今");
			String[] periodArr = timePeriodStr.split(":");
			if(periodArr[0]!=null && periodArr[0].trim().length()>0)
			{
				startDate.setText(periodArr[0].trim());
				remindStartDate = periodArr[0].trim();
				if(periodArr.length>=2 && periodArr[1]!=null && periodArr[1].trim().length()>0)
				{
					endDate.setText(periodArr[1].trim());
				}else
				{
					endDate.setText(dateList.get(0).trim());
				}
			}
		}
    	//主要指数数据
        LayoutParams chbParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); 
        chbParams.setMargins(20, 10, 0, 0);
        LayoutParams tvParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); 
        tvParams.setMargins(5, 10, 0, 0);
        List<Map<String,Object>> indexList = FundUtil1.getIndexSet();
		for(int i=0;i<indexList.size();i++)
    	{
			Map<String, Object> map = indexList.get(i);
			String name = null;
			String number = null;
			int enable = 0;
			if(map.get("name")!=null)
			{
				name = map.get("name").toString();
			}
			if(map.get("number")!=null)
			{
				number = map.get("number").toString();
			}
			if(map.get("enable")!=null)
			{
				enable = Integer.valueOf(map.get("enable").toString());
			}
			
			if(name==null || number==null || number.trim().length()==0 || enable==0)
			{
				continue;
			}
			
    		FundInfo info = FundUtil.getFundNetValueFromLocalhost(name,number);
    		CheckBox chbIndex = new CheckBox(this);
            chbIndex.setText(" ○ ");
            chbIndex.setTextSize(15);
    //        chbIndex.setTextColor(FundUtil1.getIndexColor(number));
            chbIndex.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
            chbIndex.setTag(chbIndex.getId(), info);
            chbIndex.setLayoutParams(chbParams);
            layoutIndex1.addView(chbIndex);
            
            chxIndexList.add(chbIndex);
            
            TextView textView = new TextView(this);
            textView.setText(name+"");
            textView.setTextSize(15);
            textView.setTextColor(Color.WHITE);
            textView.setLayoutParams(tvParams);
            layoutIndex1.addView(textView);
      //      if("1399905".equals(info.getNumber()))
/*            if("0000982".equals(info.getNumber()))
            {
            	selectFundInfoList.add(info);
            	chbIndex.setText("● "+name);
            	chbIndex.setChecked(true);
            }*/
            if("0000905".equals(info.getNumber()))
            {
            	selectFundInfoList.add(info);
            	chbIndex.setText(" ● ");
            	chbIndex.setTextColor(Constant.colorSet1[0]);
            	chbIndex.setChecked(true);
            }
            if("1399006".equals(info.getNumber()))
            {
				selectFundInfoList.add(info);
				chbIndex.setText(" ● ");
				chbIndex.setTextColor(Constant.colorSet1[1]);
				chbIndex.setChecked(true);
            }
            if("0000000".equals(info.getNumber()))
            {
            	fundInfo = info;
            }
    	}


//        chxIndexList.add(chxFund);
//        chxFund.setTextColor(color[18]);
    	
 //   	fundInfo = new FundInfo();
 //   	fundInfo.setName("基金");
 //   	fundInfo.setNumber("0000000");
    	
    	//给控件赋值
    	if(dateList!=null && dateList.size()>0)
    	{
    		currDate.setText("最新:"+dateList.get(0));
    	}
    	
       	orderCheckedItems = new boolean[timePeriodList.size()];
       	orderItems = new String[timePeriodList.size()];
    	for(int i=0;i<orderItems.length;i++)
    	{
    		orderItems[i] = timePeriodList.get(i).toString();
    	}
    }
    
    
    /**
     * 初始化行业指数控件
     */
    private void initIndexView()
    {
        LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.setMargins(0, 0, 15, 0);
        chxDisplayDiffLine = (CheckBox)findViewById(R.id.displayDiffLine);
        chxDisplayDiffLine.setLayoutParams(layoutParams1); 
        chxDisplayDiffLine.setChecked(true);
        chxDisplayDiffLine.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        chxChartsLine = (CheckBox)findViewById(R.id.chartsLine); 
        chxChartsLine.setLayoutParams(layoutParams1); 
        chxChartsLine.setChecked(true);
        chxChartsLine.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        chxSimpleLine = (CheckBox)findViewById(R.id.simpleLine);
        chxSimpleLine.setLayoutParams(layoutParams1); 
        chxSimpleLine.setChecked(true);
        chxSimpleLine.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        
        openFundIndex = (TextView) findViewById(R.id.openFundIndex);
        filterText = (EditText)findViewById(R.id.filter);
        orderFields = (TextView) findViewById(R.id.orderFields);
        txtIndexSet = (TextView) findViewById(R.id.indexSet);
        
        
        //放大与还原
        chxZoomIn = (CheckBox)findViewById(R.id.zoomIn);
        chxZoomIn.setLayoutParams(layoutParams1); 
        chxZoomIn.setChecked(true);
        chxZoomIn.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        //
        chxCandle = (CheckBox)findViewById(R.id.candle);
        chxCandle.setLayoutParams(layoutParams1); 
        chxCandle.setChecked(false);
        chxCandle.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        //对数坐标
		chxLogY = (CheckBox)findViewById(R.id.logY);
		chxLogY.setLayoutParams(layoutParams1);
		chxLogY.setChecked(true);
		chxLogY.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        //基金持仓按钮
        txtFundStocks = (TextView)findViewById(R.id.txtFundStocks);
        //打开交易记录列表
		txtFundTrade = (TextView)findViewById(R.id.txtFundTrade);
		//打开执行SQL窗口
		txtSqlQuery = (TextView)findViewById(R.id.txtSqlQuery);
        
    }
    
    /**
     * 注册事件
     */
    private void initListener()
    {
    	//时间范围点击弹出下拉框
    	timePeriod.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0) 
			{
				initPopWindow((TextView)arg0,timePeriodList.toArray());
			}
		});
    	
    	//时间范围文本改变事件
    	timePeriod.addTextChangedListener(new TextWatcherAdapter()
    	{
			@Override
			public void afterTextChanged(Editable arg0) 
			{
				timePeriod_afterTextChanged(arg0);
			}
    	});
    	
    	
    	
    	//界面参数改变触发drawView重绘事件
    	TextWatcher textWatcher = new TextWatcherAdapter()
    	{
        	@Override
        	public void afterTextChanged(Editable arg0) 
        	{
        		rePaintDrawView();
        	}
    	};
    	
    	startDate.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0) 
			{
				initPopWindow((TextView)arg0,dateList.toArray());
			}
		});
    	endDate.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0) 
			{
				initPopWindow((TextView)arg0,dateList.toArray());
			}
		});
    	//时间文本改变事件
    	startDate.addTextChangedListener(textWatcher);
    	endDate.addTextChangedListener(textWatcher);
    	//涨跌幅设置文本改变事件
    	positiveRate.addTextChangedListener(textWatcher);
    	negativeRate.addTextChangedListener(textWatcher);
		positiveRate1.addTextChangedListener(textWatcher);
		negativeRate1.addTextChangedListener(textWatcher);
        //基金文本改变事件
        fundSelect.addTextChangedListener(textWatcher);
        //年化线
		annualLine.addTextChangedListener(textWatcher);

    	
    	//当前日期点击弹出更新窗口
    	currDate.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0) 
			{
				fresh_onClick();
			}
		});
    	
    	//更新图标点击弹出更新窗口
    	fresh.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0)
			{
				fresh_onClick();
			}
		});
    	
    	//涨跌幅设置点击弹出下拉框
    	positiveRate.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0) 
			{
				initPopWindow((TextView)arg0,positiveArr);
			}
		});
    	negativeRate.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0) 
			{
				initPopWindow((TextView)arg0,negativeArr);
			}
		});
		positiveRate1.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				initPopWindow((TextView)arg0,positiveArr);
			}
		});
		negativeRate1.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				initPopWindow((TextView)arg0,negativeArr);
			}
		});

    	//年化线
		annualLine.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				initPopWindow((TextView)arg0,annualArr);
			}
		});
    	
    	//下拉框选中事件
    	popupList.setOnItemClickListener(new OnItemClickListener() 
    	{
    		@Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
    		{
    			tv.setText(((TextView)arg1).getText());
    			popupWindow.dismiss();
    		}
    	});
    	

    	
    	//主要指数和净值比、趋势线、拆线选择改变事件
    	OnCheckedChangeListener indexOnCheckedChangeListener = new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				indexCheckedChanged(arg0,arg1);
				arg0.setBackground(new ColorDrawable(Color.TRANSPARENT));
			}};
		OnTouchListener onTouchListener = new OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				int a = arg1.getAction();
				if(MotionEvent.ACTION_DOWN==a)
				{
			        for(int i=0;i<chxIndexList.size();i++)
			        {
			        	CheckBox chxIndex = chxIndexList.get(i);
			        	chxIndex.setBackground(new ColorDrawable(Color.TRANSPARENT));
			        }
					arg0.setBackground(new ColorDrawable(Color.WHITE));
				}
				return false;
			}
		};
        for(int i=0;i<chxIndexList.size();i++)
        {
        	CheckBox chxIndex = chxIndexList.get(i);
        	chxIndex.setOnCheckedChangeListener(indexOnCheckedChangeListener);
        	chxIndex.setOnTouchListener(onTouchListener);
        }
        chxDisplayDiffLine.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) 
			{
				if(arg0.getText()!=null)
				{
					String text = arg0.getText().toString().replace("●", "").replace("○", "");
					if(arg1)
					{
						arg0.setText("●"+text);
					}else
					{
						arg0.setText("○"+text);
					}
				}
				rePaintDrawView();
			}
        });
        chxChartsLine.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) 
			{
				if(arg0.getText()!=null)
				{
					String text = arg0.getText().toString().replace("●", "").replace("○", "");
					if(arg1)
					{
						arg0.setText("●"+text);
					}else
					{
						arg0.setText("○"+text);
					}
				}
				rePaintDrawView();
			}
        });
        chxSimpleLine.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) 
			{
				if(arg0.getText()!=null)
				{
					String text = arg0.getText().toString().replace("●", "").replace("○", "");
					if(arg1)
					{
						arg0.setText("●"+text);
					}else
					{
						arg0.setText("○"+text);
					}
				}
				rePaintDrawView();
			}
        });
        chxCandle.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
        	@Override
        	public void onCheckedChanged(CompoundButton arg0, boolean arg1) 
        	{
        		if(arg0.getText()!=null)
        		{
        			String text = arg0.getText().toString().replace("●", "").replace("○", "");
        			if(arg1)
        			{
        				arg0.setText("●"+text);
        			}else
        			{
        				arg0.setText("○"+text);
        			}
        		}
        		rePaintDrawView();
        	}
        });
        
        //基金点击弹出下拉框
        fundSelect.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View arg0) 
			{
				initFundPop((TextView)arg0);
			}
		});
        
        //基金下拉框选择事件
        fundListView.setOnItemClickListener(new OnItemClickListener() 
        {
    		@Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
    		{
    			fundListView_onItemClick(arg0,arg1,arg2,arg3);
    		}
    	});
        
        //打开基金主页事件
        openFundIndex.setOnClickListener(new OnClickListener() 
        {
			@Override
			public void onClick(View arg0) 
			{
				openFundIndex_onClick();
			}
		});
        
        //打开指数设置事件
        txtIndexSet.setOnClickListener(new OnClickListener() 
        {
			@Override
			public void onClick(View arg0) 
			{
				txtIndexSet_onClick();
			}
		});
        
    	
    	//更新图标点击弹出更新窗口
    	orderFields.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0)
			{
				orderFields_onClick(arg0);
			}
		});
        
        //放大与还原事件
        chxZoomIn.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) 
			{
				if(arg0.getText()!=null)
				{
					String text = arg0.getText().toString().replace("●", "").replace("○", "");
					if(arg1)
					{
						arg0.setText("●"+text);
					}else
					{
						arg0.setText("○"+text);
					}
				}
				/*chxZoomIn_onCheckedChanged(arg0,arg1);*/
			}
        });
        //对数坐标
		chxLogY.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1)
			{
				if(arg0.getText()!=null)
				{
					String text = arg0.getText().toString().replace("●", "").replace("○", "");
					if(arg1)
					{
						arg0.setText("●"+text);
					}else
					{
						arg0.setText("○"+text);
					}
				}
				rePaintDrawView();
			}
		});
        //基金持仓按钮点击打开基金持仓列表页面
    	txtFundStocks.setOnClickListener(new OnClickListener() 
    	{
			@Override
			public void onClick(View arg0) 
			{
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, FundStocks.class);
                for(String key:dataContext.keySet())
                {
                	intent.putExtra(key, dataContext.get(key).toString());
                }
                startActivityForResult(intent, 100);
			}
		});

		//交易按钮点击打开交易记录列表页面
		txtFundTrade.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, FundTradeList.class);
				for(String key:dataContext.keySet())
				{
					intent.putExtra(key, dataContext.get(key).toString());
				}
				startActivityForResult(intent, 100);
			}
		});

		//交易按钮点击打开交易记录列表页面
		txtSqlQuery.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, SqlQueryList.class);
				for(String key:dataContext.keySet())
				{
					intent.putExtra(key, dataContext.get(key).toString());
				}
				startActivityForResult(intent, 100);
			}
		});
        
        //drawView接触事件
/*        drawView.setOnTouchListener(new OnTouchListener() 
        {
			@Override
			public boolean onTouch(View view, MotionEvent event) 
			{
				return drawView_onTouch(view, event);
			}
		});*/
        
        //drawView接触事件
        magnifierDrawView.setOnTouchListener(new OnTouchListener() 
        {
			@Override
			public boolean onTouch(View view, MotionEvent event) 
			{
				return drawView_onTouch(view, event);
			}
		});
       
        //drawView长按事件
        drawView.setOnTouchListener(new OnTouchListener() 
        {
        	long s1 = 0;
        	long s2 = 0;
			@Override
			public boolean onTouch(View view, MotionEvent event) 
			{
				if(event.getAction()==MotionEvent.ACTION_DOWN)
				{
					s1 = System.currentTimeMillis();
				}
				if(event.getAction()==MotionEvent.ACTION_UP)
				{
					s2 = System.currentTimeMillis();
				}
				if(s2-s1>500)
				{
			//		drawView_onLongClick(view, event);
				}
				return true;
			}
		});
    }
    

    /**
     * drawView长按事件
     * @param
     * @return
     */
    protected boolean drawView_onLongClick(View view, MotionEvent event) 
    {
		FundInfo info = null;
    	String name = "";
    	tradeNumber = "";
    	if(selectFundInfoList!=null && selectFundInfoList.size()>0)
    	{
    		info = selectFundInfoList.get(0);
    		name = StringUtil.dealNull(info.getName());
    		tradeNumber = StringUtil.dealNull(info.getNumber());
    	}
    	if("0000000".equals(tradeNumber))
    	{
    		return true;
    	}
    	
    	int dateIndex = drawView.xToIndex((int)event.getX());
    	tradeDate = "";
    	if(dateList.size()>dateIndex)
    	{
    		tradeDate = dateList.get(dateIndex);
    	}


    	
    	AlertDialog.Builder builder  = new Builder(MainActivity.this);
    	builder.setTitle(tradeNumber+" "+name+" "+tradeDate+" 交易" ) ;
    	final boolean[] checkedItems = new boolean[]{false,false,false,false};
    	final CharSequence[] items = {"买入", "卖出", "取消","全部取消"};
    	int type = FundUtil1.getTradeType(tradeNumber, tradeDate);
    	int defType = 0;
    	if(type==0)
    	{
    		defType = 2;
    	}else if(type==1)
    	{
    		defType = 0;
    	}else if(type==2)
    	{
    		defType = 1;
    	}
    	checkedItems[defType] = true;
    	builder.setSingleChoiceItems(items, defType, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				for(int i=0;i<checkedItems.length;i++)
				{
					checkedItems[i] = (i==arg1);
				}
				
			}
		});
    	builder.setPositiveButton("确定",new DialogInterface.OnClickListener()
    	{
    		@Override
    		public void onClick(DialogInterface arg0, int arg1) {
    			Thread thread = new Thread()
    			{
    				public void run()
    				{
    					int type = 0;
    					if(checkedItems[0])
    					{
    						type = 1;
							FundTradeDialog dialog = new FundTradeDialog();
					//		dialog.setArguments();
							dialog.show(getFragmentManager(), "dialog_fragment");
    					}
    					if(checkedItems[1])
    					{
    						type = 2;
							FundTradeDialog dialog = new FundTradeDialog();
							dialog.show(getFragmentManager(), "dialog_fragment");
    					}
    					if(checkedItems[2])
    					{
    						type = 0;
						//	FundUtil1.saveTrade(tradeNumber, tradeDate, type);
    					}
    					if(checkedItems[3])
    					{
    						type = -1;
						//	FundUtil1.saveTrade(tradeNumber, tradeDate, type);
    					}
    				}
    			};
    			thread.start();
    		}
    	});
    	builder.setNegativeButton("取消", null);
    	builder.show();
		return true;
	}

	/**
     * 时间范围文本改变事件
     * @param arg0
     */
	protected void timePeriod_afterTextChanged(Editable arg0) 
	{
		String period = periodMap.get(timePeriod.getText().toString());
		if(period!=null && period.indexOf(":")>0)
		{
			String[] periodArr = period.split(":");
			if(periodArr[0]!=null && periodArr[0].trim().length()>0)
			{
				startDate.setText(periodArr[0].trim());
				remindStartDate = periodArr[0].trim();
				if(periodArr.length>=2 && periodArr[1]!=null && periodArr[1].trim().length()>0)
				{
					endDate.setText(periodArr[1].trim());
				}else
				{
					endDate.setText(dateList.get(0).trim());
				}
			}
		}
	}

	/**
     * 基金下拉框选择事件
     * @param arg0
     * @param arg1
     * @param arg2
     * @param arg3
     */
    protected void fundListView_onItemClick(AdapterView<?> arg0, View arg1,	int arg2, long arg3)
    {
		selectIdx = arg2;
		fundInfo.getActualValues().clear();
		if(StringUtil.isNullOrEmpty(fundList.get(arg2).get("number"))
				|| StringUtil.isNullOrEmpty(fundList.get(arg2).get("name")))
		{
			return;
		}
		final String number = fundList.get(arg2).get("number").toString();
		final String name = fundList.get(arg2).get("name").toString();
		boolean isFOF = false;
		Object isFOFObj = fundList.get(arg2).get("isFOF");
		if (isFOFObj!=null && "1".equals(isFOFObj.toString().trim()))
		{
			isFOF = true;
			fundInfo.setType(2);
		}else
		{
			fundInfo.setType(0);
		}
		shiftFund(isFOF,name,number);
	}
    
    /**
     * 切换基金
     * @param name
     * @param number
     */
    private void shiftFund(boolean isFOF,final String name,final String number)
    {
    	if (isFOF)
		{
			FOFInfo fofInfo = FOFUtil.getFOFNetValue(name,number);
			fundInfo.setActualValues(fofInfo.getActualValues());
			fundInfo.setName(name);
			fundSelect.setText(name);
			fundPopup.dismiss();

			return;
		}

		final FundInfo info = FundUtil.getFundNetValueFromLocalhost(name, number);
		if(info==null)
		{
			return;
		}
        final String lastDate = FundUtil.getFundLastDate(number);
        final String shLastDate = FundUtil.getFundLastDate("0000001");
		if(!info.getActualValues().keySet().contains(shLastDate))
		{
			new AsyncTask(){
		    	/**
		    	 * 更新UI的操作，这里面的内容是在UI线程里面执行的
		    	 */
				@Override
				protected void onPostExecute(Object result) {
					super.onPostExecute(result);
					if(result==null || !(result instanceof FundInfo))
					{
						return;
					}
					FundInfo retInfo = (FundInfo)result;
					if(retInfo.getActualValues().size()>0)
					{
						fundInfo.setActualValues(retInfo.getActualValues());
						fundInfo.setName(name);
						fundSelect.setText(name);
						Toast.makeText(MainActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
						
	        			String date = FundUtil.getFundMinDate(number);
	        			if(date!=null && date.compareTo(remindStartDate)>0)
	        			{
	        				startDate.setText(date);
	        			}else
	        			{
	        				startDate.setText(remindStartDate);
	        			}
					}else
					{
						Toast.makeText(MainActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
					}
					fundPopup.dismiss();
				}
				/**
				 * 耗时操作，这里面的内容Android系统会自动为你启动一个新的线程执
				 */
				@Override
				protected Object doInBackground(Object... arg0) {
					String name = arg0[0].toString();
					String number = arg0[1].toString();
					String lastDate = arg0[2].toString();
					String shLastDate = arg0[3].toString();
			//		FundUtil.getFundNetValueFromUrl(number,lastDate,shLastDate);
					UpdateStrategy updateStrategy = new FundNetValueUpdateStrategy(number);
					updateStrategy.updateIndex();
					FundInfo result = FundUtil.getFundNetValueFromLocalhost(name, number);
					return result;
				}}.execute(name,number,lastDate,shLastDate);
		}else
		{
			fundInfo.setActualValues(info.getActualValues());
			fundInfo.setName(name);
			fundSelect.setText(name);
			fundPopup.dismiss();

			String date = FundUtil.getFundMinDate(number);
			if(date!=null && date.compareTo(remindStartDate)>0 && dateList.contains(date))
			{
				startDate.setText(date);
			}else
			{
				startDate.setText(remindStartDate);
			}
		}
    }

	/**
     * 从网络更新数据
     */
    protected void fresh_onClick() 
    {
    	AlertDialog.Builder builder  = new Builder(MainActivity.this);
    	builder.setTitle("确认下载数据" ) ;
    	final boolean[] checkedItems = new boolean[]{true,false,false,false,false,false,false,false};
    	final CharSequence[] items = {"主要指数", "基金基本信息", "我关注的基金净值","全部基金净值","期指:伦敦金、布伦特原油","基金持仓数据","指数成分股","清理垃圾数据"};
    	builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1, boolean arg2) {
				checkedItems[arg1] = arg2;
			}
		});
    	builder.setPositiveButton("是",new DialogInterface.OnClickListener()
    	{
    		@Override
    		public void onClick(DialogInterface arg0, int arg1) {
    			final ProgressDialog proDialog = new ProgressDialog(MainActivity.this); 
    			proDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    			proDialog.setMessage("下载数据，请稍等"); 
    			proDialog.setCancelable(false);
    			proDialog.show();

    			Thread thread = new Thread()
    			{
    				public void run()
    				{
    					if(checkedItems[0])
    					{
    						proDialog.setProgress(0);
    						String code = "0000001";//上证指数
    						UpdateStrategy indexStrategy = new MixIndexStrategy(code);
    						indexStrategy.updateIndex();
    						Map<String, String> nameMap = FundUtil1.getIndexNameMap();
    						int l = nameMap.size();
    						int i = 0;
    						for(String number:nameMap.keySet())
    						{
    							i++;
    							if("XAU".equalsIgnoreCase(number) 
    									|| "OIL".equalsIgnoreCase(number)
    								|| "0000000".equalsIgnoreCase(number)
    								|| "0000001".equalsIgnoreCase(number))
    							{
    								continue;
    							}
        						UpdateStrategy indexStrategy1 = new MixIndexStrategy(number);
        						indexStrategy1.updateIndex();
        						proDialog.setProgress(100*(i+1)/l);
    						}
    					}
    					if(checkedItems[1])
    					{
    						proDialog.setProgress(0);
    						FundUtil.updateFundBaseInfo();
    						proDialog.setProgress(100);
    					}
    					if(checkedItems[2])
    					{
    						proDialog.setProgress(0);
    						List<String> myFocus = FundUtil.getMyFocusFund();
    						int l = myFocus.size();
    						
    						for(int i=0;i<l;i++)
    						{
    							String number = myFocus.get(i);
    							if(number==null)
    							{
    								continue;
    							}
    							UpdateStrategy updateStrategy = new FundNetValueUpdateStrategy(number);
    							updateStrategy.updateIndex();
    							proDialog.setProgress(100*(i+1)/l);
    						}
    					}
    					if(checkedItems[3])
    					{
    						proDialog.setProgress(0);
    						List<String> allFund = FundUtil.getAllFund();
    						int l = allFund.size();
    						for(int i=0;i<l;i++)
    						{
    							String number = allFund.get(i);
    							if(number==null)
    							{
    								continue;
    							}
    							UpdateStrategy updateStrategy = new FundNetValueUpdateStrategy(number);
    							updateStrategy.updateIndex();
    							proDialog.setProgress(100*(i+1)/l);
    						}
    					}
    					if(checkedItems[4])
    					{
    						proDialog.setProgress(0);
    						String code1 = "XAU";//伦敦金
    						String lastDate1 = FundUtil.getFundLastDate(code1);
    						if(lastDate1==null || lastDate1.trim().length()==0)
    						{
    							lastDate1 = "1996-01-02";
    						}
    						UpdateStrategy indexStrategy = new FuturesIndexStrategy(code1);
    						indexStrategy.updateIndex();
    						proDialog.setProgress(50);
    						String code2 = "OIL";//伦敦金
    						String lastDate2 = FundUtil.getFundLastDate(code2);
    						if(lastDate2==null || lastDate2.trim().length()==0)
    						{
    							lastDate2 = "2006-07-10";
    						}
    						UpdateStrategy indexStrategy1 = new FuturesIndexStrategy(code2);
    						indexStrategy1.updateIndex();
    						proDialog.setProgress(100);
    					}
    					if(checkedItems[5])
    					{
    						proDialog.setProgress(0);
    						int fundQty = FundUtil.getAllFundCount();
    						List<String> needFundList = FundStocksUtil.getNeedUpdateFundNumber();
    			//			allFund.clear();
    			//			allFund.add("002385");
    			//			FundStocksUtil.loadZZHYFL();
    			//			FundStocksUtil.loadStocksFL();
    						int l = fundQty-needFundList.size();//已更新数量
    						for(int i=0;i<needFundList.size();i++)
    						{
    							String number = needFundList.get(i);
    							if(StringUtil.isNullOrEmpty(number))
    							{
    								continue;
    							}
    							FundStocksUtil.loadFundStocks(number);
    							if(fundQty>0)
    							{
    								proDialog.setProgress(100*(l+i+1)/fundQty);
    							}
    						}
    					}
    					if(checkedItems[6])
    					{
    						proDialog.setProgress(0);
    						List<String> indexNumberList = FundStocksUtil.getIndexNumberList();
    						int j = 0;
    						for(int i=0,l=indexNumberList.size();i<l;i++)
    						{
    							String number = indexNumberList.get(i);
    							if("XAU".equalsIgnoreCase(number) 
    									|| "OIL".equalsIgnoreCase(number)
    									|| "0000001".equalsIgnoreCase(number)
    									|| "0000832".equalsIgnoreCase(number)
    								|| "0000000".equalsIgnoreCase(number))
    							{
    								j++;
    								continue;
    							}
    							if(StringUtil.isNullOrEmpty(number))
    							{
    								continue;
    							}
    							boolean isSuccess = true;
/*    							if("1399998".equalsIgnoreCase(number)//煤炭
    									|| "1399440".equalsIgnoreCase(number)//钢铁
    									|| "1399809".equalsIgnoreCase(number)//保险
    									|| "1399983".equalsIgnoreCase(number)//地产
    									)
    							{
    								isSuccess = FundStocksUtil.loadIndexStocks(number);
    							}else
    							{
    								isSuccess = FundStocksUtil.loadIndexStocks1(number);
    							}*/
    							
    							if("1399440".equalsIgnoreCase(number))//钢铁
    							{
    								isSuccess = FundStocksUtil.loadIndexStocks(number);
    							}else if("0000807".equalsIgnoreCase(number)//食品饮料
    								|| "1399707".equalsIgnoreCase(number)//证券
    								|| "1399610".equalsIgnoreCase(number)//TMT50
    								|| "1399363".equalsIgnoreCase(number))//计算机
    							{
    								isSuccess = FundStocksUtil.loadIndexStocks1(number);
    							}else
    							{
    								isSuccess = FundStocksUtil.loadIndexStocks2(number);
    							}
    							
    							if(isSuccess)
    							{
    								j++;
    							}
    							proDialog.setProgress(100*j/l);
    						}
    					}
    					if(checkedItems[7])
    					{
    						proDialog.setProgress(0);
    						boolean flag = FundUtil.clearRubbishData();
    						if(flag)
    						{
    							proDialog.setProgress(100);
    						}
    					}
    					
    	//				proDialog.dismiss();//万万不可少这句，否则会程序会卡死。
    					DBManager.closeDB();
    					finish();  
   // 					Intent intent = new Intent(MainActivity.this, MainActivity.class);  
    //					startActivity(intent);
    				}
    			};
    			thread.start();
    		}
    	});
    	builder.setNegativeButton("否", null);
    	builder.show();
	}
    
    /**
     * 初始化弹出下拉框，
     * 适用范围：时间区间、涨幅、跌幅
     * @param view
     * @param objects
     */
	@SuppressWarnings("unchecked")
	private void initPopWindow(TextView view,final Object[] objects){  
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, objects)
        {
        	@Override
        	public View getView(int position, View convertView, ViewGroup parent) {
        		TextView mTextView = new TextView(getApplicationContext());
                mTextView.setText(objects[position].toString());
                mTextView.setTextSize(15);
                mTextView.setTextColor(bg1);
                mTextView.setPadding(30, 10, 0, 10);
        		return mTextView;
        	}
        };  
        popupList.setAdapter(adapter);  
        String text = view.getText().toString();
        for(int i=0;i<objects.length;i++)
        {
        	if(text.equals(objects[i]))
        	{
        		popupList.setSelection(i);
        		break;
        	}
        }
        popupWindow.showAsDropDown(view);
        tv = view;
    }
	
	/**
	 * 初始化弹出下拉框，
	 * 适用范围：基金
	 * @param view
	 */
	private void initFundPop(TextView view){  
		String filterStr =filterText.getText().toString();
		if(filterStr!=null && filterStr.contains(">"))
		{
			String filterStr1 = filterStr.replace(">", "");
			Pattern pattern = Pattern.compile("[0-9]+"); 
			Matcher matcher = pattern.matcher((CharSequence) filterStr1); 
			if(matcher.matches())
			{
				selectIdx = Integer.valueOf(filterStr1);
				filterStr = null;
			}else
			{
				selectIdx = 0;
				filterStr = null;
			}
		}

		fundList = FundUtil.getFundListOrderByAchievement(orderFieldList,filterStr);
        FundListViewAdapter adapter = new FundListViewAdapter(this, fundList, new FundListViewAdapter.CallBack(){
			@Override
			public void img_onClickFund(View view, int position) 
			{
				focusFund_onClickFund(position); 
			}
        });
        fundListView.setAdapter(adapter); 
        fundListView.setSelection(Math.max(0, selectIdx-3));
        fundPopup.showAsDropDown(view);
    }
	
	/**
	 * drawView接触事件
	 * 1.
	 * @param view
	 * @param event
	 */
	protected boolean drawView_onTouch(View view, MotionEvent event)
	{
		if(chxZoomIn.isChecked())
		{
			return true;
		}
		int dvW = drawView.getW();
		int dvH = drawView.getH();
		int a = event.getAction();
		if(MotionEvent.ACTION_DOWN==a)
		{
			x = event.getX();
			y = event.getY(); 
			
	        String text1 = startDate.getText().toString();
	        for(int i=0;i<dateList.size();i++)
	        {
	        	if(text1.equals(dateList.get(i)))
	        	{
	        		startIndex = i;
	        		break;
	        	}
	        }
	        String text2 = endDate.getText().toString();
	        for(int i=0;i<dateList.size();i++)
	        {
	        	if(text2.equals(dateList.get(i)))
	        	{
	        		endIndex = i;
	        		break;
	        	}
	        }
	        

	        if(fundList==null || fundList.size()==0)
	        {
	    		String filterStr =filterText.getText().toString();
	    		if(filterStr!=null && filterStr.contains(">"))
	    		{
	    			String filterStr1 = filterStr.replace(">", "");
	    			Pattern pattern = Pattern.compile("[0-9]+"); 
	    			Matcher matcher = pattern.matcher((CharSequence) filterStr1); 
	    			if(matcher.matches())
	    			{
	    				selectIdx = Integer.valueOf(filterStr1);
	    				filterStr = null;
	    			}else
	    			{
	    				selectIdx = 0;
	    				filterStr = null;
	    			}
	    		}
	        	fundList = FundUtil.getFundListOrderByAchievement(orderFieldList,filterStr);
	        }
	        //双击
	        secClick = System.currentTimeMillis();
	        boolean dbClick = (secClick - firClick < 1500);
	        firClick = secClick;
	   //     if(chxFund.isChecked() && fundList!=null && dbClick){  
	        if(fundList!=null && dbClick){  
	        	//双击事件  
	        	if(y<dvH/2)//双击右上
	        	{
	        		selectIdx = Math.max(0, selectIdx-1);
	        	}else//双击右下
	        	{
	        		selectIdx = Math.min(fundList.size()-1, selectIdx+1);
	        	}
	        	if(selectIdx>=0 && selectIdx<fundList.size())
	        	{
	        		fundInfo.getActualValues().clear();
	        		Object numberObj = fundList.get(selectIdx).get("number");
	        		Object nameObj = fundList.get(selectIdx).get("name");
	        		if(numberObj!=null && nameObj!=null)
	        		{
	        			String number = fundList.get(selectIdx).get("number").toString();
	        			String name = fundList.get(selectIdx).get("name").toString();
	        			FundInfo info = FundUtil.getFundNetValueFromLocalhost(name, number);
	        			fundInfo.setActualValues(info.getActualValues());
	        			fundSelect.setText(name);
	        			
	        			String date = FundUtil.getFundMinDate(number);
	        			if(date!=null && date.compareTo(remindStartDate)>0 && dateList.contains(date))
	        			{
	        				startDate.setText(date);
	        			}else
	        			{
	        				startDate.setText(remindStartDate);
	        			}
	        		}
	        	}
	        	firClick = 0;
	        }  
//			rePaintDrawView();
		}else if(MotionEvent.ACTION_UP==a && x>dvW/3 && x<2*dvW/3)
		{
			int j = 0;
			if(event.getX()-x>100)
			{
				for(int i=0;i<timePeriodList.size();i++)
				{
					if(timePeriod.getText().toString().equals(timePeriodList.get(i)))
					{
						j = i-1;
						if(j<0)
						{
							j = timePeriodList.size()-1;
						}
						break;
					}
					
				}
				timePeriod.setText(timePeriodList.get(j));
			}
			if(event.getX()-x<-100)
			{
				
				for(int i=0;i<timePeriodList.size();i++)
				{
					if(timePeriod.getText().toString().equals(timePeriodList.get(i)))
					{
						j = i+1;
						if(j>=timePeriodList.size())
						{
							j = 0;
						}
						break;
					}
				}
				timePeriod.setText(timePeriodList.get(j));
			}
			Toast.makeText(MainActivity.this, "股市定律:7亏2平1盈", Toast.LENGTH_SHORT).show();
		}else if(MotionEvent.ACTION_MOVE==a)
		{
			float y2 = event.getY()-y;
			if(Math.abs(y2)>10)
			{
				if(x<dvW/3)
				{
					int startIndex1 = startIndex+(int)y2/10;
					if(startIndex1<=endIndex)
					{
						startIndex1 = endIndex-1;
					}
					if(startIndex1>=dateList.size())
					{
						startIndex1 = dateList.size() - 1;
					}
					if(startIndex1<=0)
					{
						startIndex1 = 1;
					}
					startDate.setText(dateList.get(startIndex1));
					remindStartDate = dateList.get(startIndex1);
				}else if(x<2*dvW/3)
				{
					
				}else
				{
					int endIndex1 = endIndex+(int)y2/10;
					if(endIndex1>=startIndex)
					{
						endIndex1 = startIndex-1;
					}
					if(endIndex1>=dateList.size()-1)
					{
						endIndex1 = dateList.size() - 2;
					}
					if(endIndex1<=0)
					{
						endIndex1 = 0;
					}
					endDate.setText(dateList.get(endIndex1));
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 打开对应基金主页
	 */
    protected void openFundIndex_onClick() 
    {
    	String number = FundUtil.getFundNumber(fundSelect.getText().toString());
    	if(StringUtil.isNullOrEmpty(number))
    	{
    		return;
    	}
    	String hyperlink = "http://m.1234567.com.cn/3g/fund/fund,"+number+".shtml";//超链接
/*    	if(isWifi(getApplicationContext()))
    	{
    		hyperlink = "http://fund.eastmoney.com/f10/ccmx_"+number+".html";//超链接
    	}*/
        Intent intent = new Intent();        
        intent.setAction("android.intent.action.VIEW");    
        Uri content_url = Uri.parse(hyperlink);   
        intent.setData(content_url);  
        startActivity(intent);
	}
    
	/**
	 * 打开指数设置
	 */
    protected void txtIndexSet_onClick() 
    {
    	DialogFragmentEx dialog = new DialogFragmentEx();
    	dialog.show(getFragmentManager(), "dialog_fragment");
	}
    
	
	/**
	 * 排序对话框
	 */
    protected void orderFields_onClick(View view) 
    {
    	AlertDialog.Builder builder  = new Builder(MainActivity.this);
    	builder.setTitle("选择排序依据组合" ) ;
    	if(timePeriodList==null || timePeriodList.size()==0)
    	{
    		return;
    	}
    	builder.setMultiChoiceItems(orderItems, orderCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1, boolean arg2) {
				orderCheckedItems[arg1] = arg2;
			}
		});
    	builder.setPositiveButton("是",new DialogInterface.OnClickListener()
    	{
    		@Override
    		public void onClick(DialogInterface arg0, int arg1) {
    			Thread thread = new Thread()
    			{
    				public void run()
    				{
    					orderFieldList.clear();
    					for(int i=0;i<orderCheckedItems.length;i++)
    					{
    						if(orderCheckedItems[i])
    						{
    							String period = periodMap.get(timePeriodList.get(i));
    							if(period!=null)
    							{
    								orderFieldList.add(period);
    							}
    						}
    					}
    				}
    			};
    			thread.start();
    		}
    	});
    	builder.setNegativeButton("否", null);
    	builder.show();
	}
    
    @Override
    protected void onResume() 
    {
    	if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)//横屏
    	{ 
    //		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
    	}
    	super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * 重绘drawView界面
     */
    public void rePaintDrawView()
    {
		String regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
    	String sDate = startDate.getText().toString();
    	String eDate = endDate.getText().toString();
		if(Pattern.matches(regex, sDate) && Pattern.matches(regex, eDate))
		{
			ParamInfo paramInfo = new ParamInfo();
			paramInfo.setStartDate(sDate);
			paramInfo.setEndDate(eDate);
	    	String pRate = positiveRate.getText().toString().replace("涨", "");
	    	String nRate = negativeRate.getText().toString().replace("跌", "-");
	    	paramInfo.setPositiveRate(pRate);
	    	paramInfo.setNegativeRate(nRate);
			String pRate1 = positiveRate1.getText().toString().replace("涨", "");
			String nRate1 = negativeRate1.getText().toString().replace("跌", "-");
			paramInfo.setPositiveRate1(pRate1);
			paramInfo.setNegativeRate1(nRate1);
	    	paramInfo.setSelectFundInfoList(selectFundInfoList);
	    	paramInfo.setDisplayDiffLine(chxDisplayDiffLine.isChecked());
	    	paramInfo.setChartsLine(chxChartsLine.isChecked());
	    	paramInfo.setSimpleLine(chxSimpleLine.isChecked());
	    	paramInfo.setCandle(chxCandle.isChecked());
			paramInfo.setLogY(chxLogY.isChecked());
			String account = "";
			String fundName = fundSelect.getText().toString();
			if (fundInfo.getType()==2 || "基金".equals(fundName))//FOF
			{
				account = fundName;
			}
			paramInfo.setAccount(account);
			//年化
			String annualStr = annualLine.getText().toString().replace("年化", "").replace("线", "");
			double annual = 0;
			if(!StringUtil.isNullOrEmpty(annualStr))
			{
				annual = Double.valueOf(annualStr);
			//	annualFund = FundUtil
			}
			paramInfo.setAnnual(annual);
	    	drawView.rePaintDrawView(paramInfo);
	    	
	    	magnifierDrawView.rePaintDrawView(paramInfo);
	    	
/*			ParamInfo paramInfo1 = new ParamInfo();
			paramInfo1.setStartDate(sDate);
			paramInfo1.setEndDate(eDate);
	    	String pRate1 = positiveRate.getText().toString().replace("涨", "");
	    	String nRate1 = negativeRate.getText().toString().replace("跌", "-");
	    	paramInfo1.setPositiveRate(pRate1);
	    	paramInfo1.setNegativeRate(nRate1);
	    	paramInfo1.setSelectFundInfoList(selectFundInfoList);
	    	paramInfo1.setDisplayDiffLine(chxDisplayDiffLine.isChecked());
	    	paramInfo1.setChartsLine(chxChartsLine.isChecked());
	    	paramInfo1.setSimpleLine(chxSimpleLine.isChecked());
	    	paramInfo1.setCandle(chxCandle.isChecked());
	    	magnifierDrawView.rePaintDrawView(paramInfo);*/
		}
    }
    
    /**
     * 构造选择的指数对象列表
     */
	public void indexCheckedChanged(CompoundButton arg0, boolean arg1) 
	{
		if(arg0.getText()!=null)
		{
	//		String text = arg0.getText().toString().replace("●", "").replace("○", "");
			if(arg1)
			{
				arg0.setText(" ● ");
			}else
			{
				arg0.setText(" ○ ");
			}
		}

		Object obj = arg0.getTag(arg0.getId());
		if(obj instanceof FundInfo)
		{
			if(selectFundInfoList.contains(obj))
			{
				selectFundInfoList.remove(obj);
			}
			if(arg1)
			{
				FundInfo fund = (FundInfo)obj;
				int n = 3;
				if("0000000".equals(fund.getNumber()) || selectFundInfoList.contains(fundInfo))
				{
					n = 4;
				}
				if (selectFundInfoList.size()>=n)//最多可选择4个
				{
					selectFundInfoList.remove(selectFundInfoList.size()-1);
				}
				selectFundInfoList.add((FundInfo)obj);
			}
		}

		for(CheckBox box : chxIndexList)
		{
			Object obj1 = box.getTag(box.getId());
			if(obj1 instanceof FundInfo)
			{
				int idx = selectFundInfoList.indexOf((FundInfo)obj1);
				if (idx>=0)
				{
					box.setTextColor(Constant.colorSet1[Math.min(idx,Constant.colorSet1.length-1)]);
				}else
				{
					box.setTextColor(Color.WHITE);
					box.setText(" ○ ");
					box.setChecked(false);
				}
			}

		}

		if(selectFundInfoList.size()>1)
		{
			String minDate = null;
			for(int i=1;i<selectFundInfoList.size();i++)
			{
				FundInfo info = selectFundInfoList.get(i);
				String date = FundUtil.getFundMinDate(info.getNumber());
				if(date==null || date.trim().length()==0)
				{
					continue;
				}
				if(minDate == null)
				{
					minDate = date;
				}
				if(date.compareTo(minDate)<0)
				{
					minDate = date;;
				}
			}

			if(minDate!=null && minDate.compareTo(remindStartDate)>0 && dateList.contains(minDate))
			{
				startDate.setText(minDate);
			}else
			{
				startDate.setText(remindStartDate);
			}
		}
		
		rePaintDrawView();
		
		//计算指数之间的相关系数
/*		if(selectFundInfoList.size()>0)
		{
			FundInfo info = selectFundInfoList.get(selectFundInfoList.size()-1);
			if("0000000".equals(info.getNumber()))
			{
				correlTextView.setText("相关系数:");
			}else
			{
				new AsyncTask(){
					private String number;
			    	*//**
			    	 * 更新UI的操作，这里面的内容是在UI线程里面执行的
			    	 *//*
					@Override
					protected void onPostExecute(Object result) {
						super.onPostExecute(result);
						try {
							int i=0;
							String text = "";
							List<Map.Entry<String,Double>> mappingList = (List<Map.Entry<String,Double>>)result;
							Map<String, String> indexNameMap = FundUtil1.getIndexNameMap();
							for(Map.Entry<String,Double> mapping:mappingList)
							{ 
								if(number.equals(mapping.getKey()) || "0000000".equals(mapping.getKey()))
								{
									continue;
								}
								if(i==0)
								{
									text = indexNameMap.get(mapping.getKey())+"("+mapping.getValue()+")";
								}else
								{
									text = text+"   "+indexNameMap.get(mapping.getKey())+"("+mapping.getValue()+")";
									
								}
								i++;
							}
							Integer c = FundUtil1.getIndexColor(number);

							if(c==null)
							{
								c = Constant.colorSet[0];
							}
							correlTextView.setText("相关系数:"+text);
				//			correlTextView.setTextColor(FundUtil1.getIndexColor(number));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					*//**
					 * 耗时操作，这里面的内容Android系统会自动为你启动一个新的线程执
					 *//*
					@Override
					protected Object doInBackground(Object... arg0) {
						number = arg0[0].toString();
						List<Map.Entry<String,Double>> mappingList = FundUtil1.getCorrel(number);
						return mappingList;
					}}.execute(info.getNumber());
			}
		}*/
	}
	
	/**
	 * 关注、取消关注基金
	 * @param
	 */
	private void focusFund_onClickFund(int position)
	{
		if(fundList==null || fundList.size()<position-1)
		{
			return;
		}
		Map<String, Object> fundMap = fundList.get(position);
		Object isFOFObj = fundMap.get("isFOF");
		if (isFOFObj!=null && isFOFObj.toString().trim().equals("1"))
		{
			return;
		}
		Object numberObj = fundMap.get("number");
		Object name = fundMap.get("name");
		if(numberObj!=null)
		{
			final String number = numberObj.toString();
			
	    	AlertDialog.Builder builder  = new Builder(MainActivity.this);
	    	builder.setTitle("确认" ) ;
	    	builder.setMessage("你确定要关注/取消关注基金\""+name+"\"？" ) ; 
	    	builder.setPositiveButton("是",new DialogInterface.OnClickListener()
	    	{
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					
					FundUtil.focusOrCancelFocusFund(number);
					Toast.makeText(MainActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
				}
	    	});
	    	builder.setNegativeButton("否", null);
	    	builder.show();
		}
	}
	 
    public Map<String, Object> getDataContext() {
		return dataContext;
	}

	public void setDataContext(Map<String, Object> dataContext) {
		this.dataContext = dataContext;
	}

	/** 
     * make true current connect service is wifi 
     * @param mContext 
     * @return 
     */  
    private boolean isWifi(Context mContext) {  
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWifi.isConnected()) 
        {
        	return true;
        }  
        return false;  
    }
    
    @Override
    public void onBackPressed() 
    {
    	
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
    	if(data!=null)
    	{
        	Bundle bundle = data.getExtras();
        	if(bundle!=null)
        	{
            	for(String key:bundle.keySet())
            	{
            		dataContext.put(key, bundle.get(key));
            	}
        	}
    	}
		if(!StringUtil.isNullOrEmpty(dataContext.get("selectionName"))
				&& !StringUtil.isNullOrEmpty(dataContext.get("selectionNumber")))
		{
			final String number = dataContext.get("selectionNumber").toString();
			final String name = dataContext.get("selectionName").toString();
			shiftFund(false,name,number);
		}
    }
    
}



